package com.halden.TRPG.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.halden.TRPG.common.CodeEnum;
import com.halden.TRPG.common.MyException;
import com.halden.TRPG.entity.CardEntity;
import com.halden.TRPG.service.CardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
@Transactional(rollbackFor = MyException.class)
@Slf4j
public class CardServiceImpl implements CardService {

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public CodeEnum setCharacter(String uid, Long rid, String attributeStr) {
        //如果不存在该房间的人物卡集合，则创建一个集合
        String collectionName = rid.toString();
        if (!mongoTemplate.collectionExists(collectionName)){
            mongoTemplate.createCollection(collectionName);
        }
        CardEntity cardEntity = new CardEntity();
        cardEntity.setUid(uid);
        cardEntity.setAttributes(new HashMap<String, Integer>());
        log.info(attributeStr);
        Map attributes = JSONObject.parseObject(attributeStr,Map.class);
        for (Object obj : attributes.entrySet()){
            Map.Entry entry = (Map.Entry) obj;
            cardEntity.getAttributes().put((String) entry.getKey(),Integer.parseInt((String)entry.getValue()));
        }
        CardEntity insert = mongoTemplate.save(cardEntity,collectionName);
        if (insert != null){
            return CodeEnum.SUCCESS;
        }else{
            throw new MyException(CodeEnum.OPTION_FAIL_EXCEPTION);
        }
    }

    @Override
    public CodeEnum getAttribute(String uid, Long rid, String attributeName) {
        Criteria criteria = Criteria.where("_id").is(uid);
        Query query = new Query(criteria);
        CardEntity cardEntity = mongoTemplate.findOne(query, CardEntity.class, rid.toString());
        if (cardEntity != null){
            return CodeEnum.SUCCESS.setData(cardEntity.getAttributes().get(attributeName));
        } else {
            throw new MyException(CodeEnum.OPTION_FAIL_EXCEPTION);
        }
    }
}
